package com.ebt.m.customer.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.ebt.m.customer.cache.CustomerGetStateCache;
import com.ebt.m.customer.item.Contact;
import com.ebt.m.customer.listener.IView;
import com.ebt.m.customer.model.CustomerGetState;
import com.ebt.m.customer.view.CustomerGetView;

import java.util.HashMap;
import java.util.List;

public class AdapterCustomerGet extends BaseAdapter{

	private List<Contact> mContactsForCustomerGet;
	private Context mContext;
	
	private LruCache<String, Bitmap> mBitmapCache;
    private int MAXMEMONRY = 0;
	
    private HashMap<String, CustomerGetState> mCustomerGetCache;

    private CustomerGetStateCache mCustomerGetStateCache;


	public AdapterCustomerGet(Context context, List<Contact> contacts){
		this.mContext = context;
		this.mContactsForCustomerGet = contacts;

		if (MAXMEMONRY == 0) {
			MAXMEMONRY = (int ) (Runtime.getRuntime().maxMemory());
		}
		
		if (mBitmapCache == null) {
            mBitmapCache = new LruCache<String, Bitmap>(MAXMEMONRY / 8) {
            	
                 @Override
                 protected int sizeOf(String key, Bitmap bitmap) {
                	 return bitmap.getByteCount();
                 }

                 @Override
                 protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                	 if (evicted && oldValue != null && !oldValue.isRecycled()) {
                		 oldValue.recycle();
                		 oldValue = null;
                	 }
                 }
            };
		}
		
		if(mCustomerGetCache == null){
			mCustomerGetCache = new HashMap<String, CustomerGetState>();
		}
		
		if(mCustomerGetStateCache == null){
			mCustomerGetStateCache = new CustomerGetStateCache();
		}

		mCustomerGetStateCache.bitmapCache = mBitmapCache;

		mCustomerGetStateCache.customerGetCache = mCustomerGetCache;

	}
	
	@Override
	public int getCount() {
		return mContactsForCustomerGet.size();
	}

	@Override
	public Object getItem(int position) {
		return mContactsForCustomerGet.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		IView iView = null;
        if (null == convertView){

            iView = new CustomerGetView(mContext);
            iView.setStateCache(mCustomerGetStateCache);
            convertView = iView.getView();
            convertView.setTag(iView);
            
        }else{
        	iView = (IView) convertView.getTag();
        }
        
        iView.update(mContactsForCustomerGet.get(position));
        
        return convertView;
	}

}
